﻿using System;
using System.IO;
using System.Net;

namespace PodcastGenerator
{
    public class SermonDownloader : ISermonDownloader
    {
        private readonly string _storeLocation;
        private readonly WebClient _client;

        public SermonDownloader(string storeLocation)
        {
            if (!Directory.Exists(storeLocation))
            {
                Directory.CreateDirectory(storeLocation);
            }
            
            _storeLocation = storeLocation;
            _client = new WebClient();
        }

        public bool Download(ISermon sermon)
        {
            var saveLocation = GetSaveLocation(sermon);
            if (!File.Exists(saveLocation))
            {
                try
                {
                    _client.DownloadFile(sermon.DownloadUri, saveLocation);

                }
                catch (ArgumentNullException)
                {
                    sermon.Downloaded = false;
                    return false;
                }
                catch (WebException)
                {
                    sermon.Downloaded = false;
                    return false;
                }
                
            }

            sermon.Downloaded = true;
            return true;
        }

        public bool ExistInStoreLocation(ISermon sermon)
        {
            return File.Exists(GetSaveLocation(sermon));
        }

        private string GetSaveLocation(ISermon sermon)
        {
            return string.Format("{0}\\{1}_{2}_{3}.mp3", _storeLocation, sermon.Date.ToString("yyyyMMdd"), CleanFileName(sermon.Pastor), CleanFileName(sermon.Title));
        }

        private static string CleanFileName(string dirty)
        {
            return dirty.Replace("?", string.Empty).Replace(":", string.Empty).Replace(@"""", string.Empty).Replace("*", string.Empty);
        }
    }
}